<template>
  <div>
  <el-dialog title="项目采购申请" :visible.sync="isShow" @close = "closeDialog">

    <el-form :model="proForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :inline = "true">
  <!-- <el-form-item>
    <span>采购申请基本信息</span>
    <el-button type="primary" @click="submitForm">确定</el-button>
    <el-button @click="closeDialog">取消</el-button>
  </el-form-item> -->

  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 20px; padding: 0 12px;">
    <span style="font-size: 16px; font-weight: bold;">采购申请基本信息</span>
    <div v-if="prButShow && role == 0">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button type="primary" @click="saveForm">保存</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
    <div v-if="role != 0 && prButShow">
      <el-button type="primary" @click="approveRequest">批准</el-button>
      <el-button type="primary" @click="returnRequest">退回</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
  <br>
  <div v-if="role == 0">
  <el-form-item label="申请表单编号">
    <el-input v-model="proForm.prNum" readonly placeholder="自动生成，无需填写"></el-input>
  </el-form-item>
  <el-form-item label="申请时间" prop="date">
    <el-input type="date" v-model="proForm.date" style="width: 205px;"></el-input>
  </el-form-item>
  <br>
  <el-form-item label="申请人" prop="prName">
    <el-input v-model="proForm.prName" ></el-input>
  </el-form-item>
  <el-form-item label="所属部门" >
    <el-input v-model="deptName" readonly></el-input>
  </el-form-item>
  <br>
  <el-form-item label="项目名称" prop="pid">
    <el-select v-model="proForm.pid" clearable="true" filterable style="width: 205px;" placeholder="请选择项目类别" @change="getValue">
        <el-option v-for="project in projectDate" :label="project.pname" :value="project.pid" :key="project.pid"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="预估产值">
    <el-input v-model="proForm.ouputvalue" readonly></el-input>
  </el-form-item>
  <br>
  <el-form-item label="预估外购金额">
    <el-input v-model="proForm.estimatevalue" readonly></el-input>
  </el-form-item>
  <el-form-item label="审核状态">
    <el-select placeholder="请选择节点" v-model="proForm.status" style="width: 205px;" disabled>
                <el-option label="未提交" :value="0"></el-option>
                <el-option label="部门经理审核" :value="1"></el-option>
                <el-option label="总经理审核" :value="2"></el-option>
                <el-option label="已完成" :value="3"></el-option>
              </el-select>
  </el-form-item>
  <br>
  <div class="form-row-full">
  <el-form-item label="采购事由" prop="reason">
    <el-input type="textarea" v-model="proForm.reason" style="width: 525px;" :rows="2"></el-input>
  </el-form-item>
  </div>
</div>


<div v-if="role != 0">
  <el-form-item label="申请表单编号">
    <el-input v-model="proForm.prNum" readonly placeholder="自动生成，无需填写"></el-input>
  </el-form-item>
  <el-form-item label="申请时间">
    <el-input type="date" v-model="proForm.date" style="width: 205px;" disabled></el-input>
  </el-form-item>
  <br>
  <el-form-item label="申请人" >
    <el-input v-model="proForm.prName" readonly></el-input>
  </el-form-item>
  <el-form-item label="所属部门" >
    <el-input v-model="proForm.dname" readonly></el-input>
  </el-form-item>
  <br>
  <el-form-item label="项目名称">
    <el-select v-model="proForm.pid" clearable="true" filterable style="width: 205px;" disabled>
        <el-option v-for="project in projectDate" :label="project.pname" :value="project.pid" :key="project.pid"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="预估产值">
    <el-input v-model="proForm.ouputvalue" readonly></el-input>
  </el-form-item>
  <br>
  <el-form-item label="预估外购金额">
    <el-input v-model="proForm.estimatevalue" readonly></el-input>
  </el-form-item>
  <el-form-item label="审核状态">
    <el-select placeholder="请选择节点" v-model="proForm.status" style="width: 205px;" disabled>
                <el-option label="未提交" :value="0"></el-option>
                <el-option label="部门经理审核" :value="1"></el-option>
                <el-option label="总经理审核" :value="2"></el-option>
                <el-option label="已完成" :value="3"></el-option>
              </el-select>
  </el-form-item>
  <br>
  <div class="form-row-full">
  <el-form-item label="采购事由">
    <el-input type="textarea" v-model="proForm.reason" style="width: 525px;" :rows="2" readonly></el-input>
  </el-form-item>
  </div>
</div>




  <br>
  <div class="form-row-full" v-if="role != 1">
  <el-form-item label="部门经理审核">
    <el-input type="textarea" v-model="proForm.firstView" style="width: 525px;" :rows="2" disabled></el-input>
  </el-form-item>
  </div>
  <br>
  <div class="form-row-full" v-if="role == 1">
  <el-form-item label="部门经理审核">
    <el-input type="textarea" v-model="proForm.firstView" style="width: 525px;" :rows="2"></el-input>
  </el-form-item>
  </div>
  <br>
  <div class="form-row-full" v-if="role != 2">
  <el-form-item label="总经理审核">
    <el-input type="textarea" v-model="proForm.secondView" style="width: 525px;" :rows="2" disabled></el-input>
  </el-form-item>
  </div>
  <br>
  <div class="form-row-full" v-if="role == 2">
  <el-form-item label="总经理审核">
    <el-input type="textarea" v-model="proForm.secondView" style="width: 525px;" :rows="2"></el-input>
  </el-form-item>
  </div>

  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 20px; padding: 0 12px;">
    <span style="font-size: 16px; font-weight: bold;">本次采购信息</span>
    <div v-if="role == 0 && prButShow">
      <el-button type="primary" @click="addPd">新增</el-button>
      <el-button @click="delPd">删除</el-button>
    </div>
  </div>
  <el-row>
        <el-col>
          <el-table
            ref="multipleTable"
            :data="pdList"
            border
            stripe
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              label="类别"
              align="center"
              width="120">
              <template slot-scope="scope">{{ scope.row.ptName}}</template>
            </el-table-column>
            <el-table-column
            
              label="产品名称"
              width="120">
              <template slot-scope="scope">{{ scope.row.pdName}}</template>
            </el-table-column>
            <el-table-column
  
              label="供应商信息"
              show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.sname}}</template>
            </el-table-column>
            <el-table-column
  
              label="数量"
              show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.number}}</template>
            </el-table-column>
            <el-table-column          
          label="单价"
          show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.price}}</template>
          </el-table-column>
          <el-table-column
          
          label="单位"
          show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.unit}}</template>
        </el-table-column>
          <el-table-column          
          label="建议采购金额"
          show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.price * scope.row.number}}</template>
          </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div style="text-align: right;">合计:{{totalMoney}}元</div>

      <br>

  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 20px; padding: 0 12px;">
    <span style="font-size: 16px; font-weight: bold;">历史采购信息</span>
    <span style="font-size: 16px; font-weight: bold;">项目合计花费：{{ allMoney }}</span>
  </div>
  <el-row>
        <el-col>
          <el-table
            ref="multipleTable"
            :data="hisList"
            border
            stripe
            tooltip-effect="dark"
            style="width: 100%">
            <!-- <el-table-column
              type="selection"
              width="55">
            </el-table-column> -->
            <el-table-column
              label="申请单编号"
              align="center"
              width="120">
              <template slot-scope="scope">{{ scope.row.prNum}}</template>
            </el-table-column>
            <el-table-column
            
              label="项目名称"
              width="120">
              <template slot-scope="scope">{{ scope.row.pname}}</template>
            </el-table-column>
            <el-table-column
  
              label="申请人"
              show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.prName}}</template>
            </el-table-column>
            <el-table-column
  
              label="预算金额"
              show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.money}}</template>
            </el-table-column>
            <el-table-column
          
              label="建议采购金额"
              show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.money}}</template>
            </el-table-column>
            <el-table-column          
          label="当前节点"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.status" style="width: 205px;" disabled>
                <el-option label="未提交" :value="0"></el-option>
                <el-option label="部门经理审核" :value="1"></el-option>
                <el-option label="总经理审核" :value="2"></el-option>
                <el-option label="已完成" :value="3"></el-option>
            </el-select>
            </template>
          </el-table-column>
          </el-table>
        </el-col>
      </el-row>

</el-form>
</el-dialog>
<pro-detail-info :pdShow = "pdShow" :thePrNum = "proForm.prNum"  @closeDialog = "setPdShow" @pdSave = "tableLoad"></pro-detail-info>
  </div>
</template>

<script>
import proDetailInfo from './proDetailInfo.vue';
export default {
    name:'proInfo',
    props:{
        //接收父组件的数据
        isShow: Boolean, 
        proInfo: Object,
        deptDate:Array,
        mod:Number,
        role:Number,
        nowdeptno:Number,
        projectDate: Array
    },
    components:{
      proDetailInfo
    },
    data(){
        return{
            //可以不要
            dialogFormVisible: false,
            //员工基本信息
            proForm:{
                prid:0,
                pid:null,
                pname:'',
                prNum:'',
                pname:'',
                prName:'',
                date:'',
                dname:'',
                money:0,
                reason:'',
                firstView:'',
                secondView:'',
                status: 0,
                ouputvalue:'',
                estimatevalue:'',
                ptName:'',
                sID:0,
                number:0,
                price:0,
                unit:''
            },
            hasNewPd:0,
            totalMoney:0,
            prButShow: true, 
             rules: {
                 prName: [
                     { required: true, message: '请输入申请人姓名', trigger: 'blur' },
                    //  { min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                 ],
                  date: [
                       {required: true, message: '请选择日期，建议选择当天时间', trigger: 'change' }
                   ],
                  pid: [
                      {required: true, message: '请选择项目', trigger: 'change' }
                 ],
                 reason: [
                     {required: true, message: '请填写申请理由', trigger: 'blur'},
                 ]
             } ,
            //代表部门信息
            deptName:'',
            pdList:[],
            hisList:[],
            checkedPdList:[],
            pList:[],
            pdidList:[],
            empShow:false,
            allMoney:0
        }
    },
    methods:{
      getDetails(){
        // let over = 0
       
        this.$http.post("/getPd/" + this.proForm.prNum).then(res => {
          console.log(res)
          this.pdList = res.data
          // over = 1
        })
        // if(over = 1){
        //   over = 0
        //   for(pd in pdList){
        //     totalMoney += pd.price * pd. number
        //   }
        // }
      },
      handleSelectionChange(val){
        this.checkedPdList = val
      },
      getHistory(){
        if (this.proForm.pid === null || this.proForm.pid === undefined || this.proForm.pid === '') {
            return;
        }
        this.allMoney = 0
        this.$http.post("/getHisPro/" + this.proForm.pid).then(res => {
          console.log(res)
          this.hisList = res.data
          if (!this.hisList || this.hisList.length === 0) {
              this.allMoney = 0; // 空数据时总和设为 0
              return;
          }
          for (let item of this.hisList) {
              const money = Number(item.money) || 0; 
              this.allMoney += money;
          }
        })
      },
      addPd(){
        this.$refs['ruleForm'].validate((valid) => {
            //valid代表验证结果
            if (valid) {
        this.pdShow = true
        this.getDetails()
        this.getHistory()
      } 
    });
      },
      delPd(){
        if(this.checkedPdList.length == 0){
            this.$message.warning("请选择要删除的员工信息")
            return
          }
          //确认是否要删除
          this.$confirm('确定要删除选中的数据吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //then代表点击确定后的动作
            let pdids = []
            for(let pd of this.checkedPdList){
              pdids.push(pd.pdid)
            }
            //调用后台执行删除
            this.$http.post('/delPd',pdids,{ headers: { 'Content-Type': 'application/json' } }).then(res =>{
              if(res.data === 'success'){
                this.$message.success('删除成功')
                this.getDetails()
                this.getHistory()
                ///////////////////////////////
                this.pdidList = this.pdidList.filter(item => {
                // 如果pdids中不包含当前item，则保留；否则过滤掉
                  return !pdids.includes(item);
                });
                ///////////////////////////////
              } else{
                this.$message.error('删除失败')
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
      },
      setPdShow(){
          //弹窗关闭
          this.pdShow = false
        },
        submitForm(){
            //数据的提交
            //ruleForm相当于表单唯一标识
            this.$refs['ruleForm'].validate((valid) => {
            //valid代表验证结果
            if (valid) {//true代表校验通过，可以将数据提交给后台
                //执行保存或者更新动作
                this.$http.post('/subPr/' + this.proForm.prid).then(res =>{
                    if(res.data === 'success'){
                        this.$emit('proSub',res.data)
                    } else{
                        this.$message.error("请先保存申请信息")
                    }
                })
            } 
        });
        },
        saveForm(){
          this.$refs['ruleForm'].validate((valid) => {
            if(this.allMoney <= this.proForm.estimatevalue){
                this.hasNewPd = 0
            //valid代表验证结果
            if (valid) {//true代表校验通过，可以将数据提交给后台
                //提交数据给后台
                //根据主键信息来判断是更新还是新增一个员工
                let url = '/addPr'
                if(this.proForm.prid != 0){
                    url = '/updatePr'
                }
                //执行保存或者更新动作
                this.$http.post(url,this.proForm).then(res =>{
                    if(res.data === 'success'){
                        this.$emit('proSave',res.data)
                        this.pdidList = []
                        this.hasNewPd = 0
                    } else{
                        this.$message.error("服务器错误")
                    }
                })
            } 
          } else{
              this.$message.error("超出最大外购金额，无法保存本次数据")
            }
        });
        },
        getValue(pid){
          if(pid != 0){
            this.getHistory()
          this.$http.post("/selectValue/" + pid).then(res =>{
             this.proForm.estimatevalue = res.data[0].estimatevalue
             this.proForm.ouputvalue = res.data[0].ouputvalue
          }) 
        }else{
          this.proForm.estimatevalue = ''
          this.proForm.ouputvalue = ''
          }
        },
        // 修改为 async 函数，支持 await 关键字
closeDialog() {
  // 定义一个内部异步函数处理逻辑
  const handleClose = async () => {
    // 1. 检查是否需要执行删除操作
    if (this.pdidList.length !== 0 && this.hasNewPd === 1) {
      try {
        // 显示确认弹窗，等待用户选择
        await this.$confirm(
          '未保存采购申请表，是否删除本次新添加的采购明细数据?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 用户点击“确定”：执行删除请求（等待请求完成）
        const pdids = this.pdidList;
        const res = await this.$http.post(
          '/delPd',
          pdids,
          { headers: { 'Content-Type': 'application/json' } }
        );

        // 根据删除结果处理
        if (res.data === 'success') {
          this.$message.success('已删除新添加的采购明细');
          this.hasNewPd = 0;
          this.pdidList = [];
        } else {
          this.$message.error('删除失败');
        }
      } catch (err) {
        // 用户点击“取消”或确认弹窗被关闭（不执行删除）
        if (err === 'cancel') {
          // 取消操作无需提示，直接进入关闭流程
        } else {
          this.$message({ type: 'info', message: '已取消删除' });
        }
        // 无论哪种取消情况，都继续执行关闭逻辑
      }
    }

    // 2. 执行关闭弹窗的逻辑（删除完成后或无需删除时）
    this.prButShow = true;
    this.deptName = '';
    this.proForm = {
      prid: 0,
      pid: null,
      pname: '',
      prNum: '',
      prName: '',
      date: '',
      dname: '',
      money: 0,
      reason: '',
      status: 0,
      ouputvalue: '',
      estimatevalue: '',
      ptName: '',
      sID: 0,
      number: 0,
      price: 0,
      unit: ''
    };
    this.pList = [];
    this.pdList = [];
    this.hisList = [];
    this.dialogFormVisible = false;
    this.$emit('closeDialog'); // 通知父组件关闭
    if (this.$refs['ruleForm']) {
      this.$refs['ruleForm'].resetFields(); // 重置表单验证
    }
  };

  // 执行内部异步函数
  handleClose();
},
        // closeDialog(){
        //     ////////////////////////////////////////////////////////////////
        //     //确认是否要删除
        //     if(this.pdidList.length != 0){
        //     if(this.hasNewPd == 1){
        //     this.$confirm('未保存采购申请表，是否删除本次新添加的采购明细数据?', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).then(() => {
        //     //then代表点击确定后的动作
        //     let pdids = this.pdidList
        //     //调用后台执行删除
        //     this.$http.post('/delPd',pdids,{ headers: { 'Content-Type': 'application/json' } }).then(res =>{
        //       if(res.data == 'success'){
        //         this.$message.success('已删除新添加的采购明细')
        //         // this.getDetails()
        //         // this.getHistory()
        //         this.hasNewPd = 0;
        //         this.pdidList = [];
        //       } else{
        //         this.$message.error("删除失败")
        //       }
        //     })
        //   }).catch(() => {
        //     this.$message({
        //       type: 'info',
        //       message: '已取消删除'
        //     });          
        //   });
        // }
        // }
        //   //////////////////////////////////////////////////////
        //     //重置数据并关闭弹框
        //     this.prButShow = true
        //     this.deptName = ''
        //     this.proForm = {
        //         prid:0,
        //         pid:null,
        //         pname:'',
        //         prNum:'',
        //         pname:'',
        //         prName:'',
        //         date:'',
        //         dname:'',
        //         money:0,
        //         reason:'',
        //         status: 0,
        //         ouputvalue:'',
        //         estimatevalue:'',
        //         ptName:'',
        //         sID:0,
        //         number:0,
        //         price:0,
        //         unit:''
        //     }
        //     this.pList = [];
        //     this.pdList = [];
        //     this.hisList = [];
        //     this.dialogFormVisible = false
        //     //告诉父组件弹窗关闭，让父组件设置isShow为false
        //     this.$emit('closeDialog')
        //     //重置验证信息
        //     this.$refs['ruleForm'].resetFields();
        // },
        approveRequest(){
            //数据的提交
            //ruleForm相当于表单唯一标识
            this.$refs['ruleForm'].validate((valid) => {
            //valid代表验证结果
            if (valid) {//true代表校验通过，可以将数据提交给后台
                //执行保存或者更新动作
                this.$http.post('/approvePr',this.proForm).then(res =>{
                    if(res.data === 'success'){
                        this.$emit('proSub',res.data)
                    } else{
                        this.$message.error("服务器错误")
                    }
                })
            }
                      //弹窗关闭
          this.closeDialog() 
        });
        },
        returnRequest(){
            //数据的提交
            //ruleForm相当于表单唯一标识
            this.$refs['ruleForm'].validate((valid) => {
            //valid代表验证结果
            if (valid) {//true代表校验通过，可以将数据提交给后台
                //执行保存或者更新动作
                this.$http.post('/returnPr',this.proForm).then(res =>{
                    if(res.data === 'success'){
                        this.$emit('proSub',res.data)
                    } else{
                        this.$message.error("服务器错误")
                    }
                })
            } 
            //弹窗关闭
            this.closeDialog()
        });
        },
        tableLoad(msg){
          if(msg.message === 'success'){
            //关闭弹窗
            this.pdShow = false
            this.pdidList.push(msg.pdid)
            //提示信息并刷新表单
            this.$message.success("新增成功")
            this.getDetails()
            this.getHistory()
            this.hasNewPd = 1
          }
        },
        getDeptName(){
          console.log('部门号' + this.nowdeptno)
          if(this.nowdeptno != ''){
          this.$http.post('/getDname/' + this.nowdeptno).then(res =>{
            this.deptName = res.data
            })
          }
        },
        getProjectList(){
        //根据实际登陆的员工部门号信息为准//////////////////////////////////////////
        this.$http.get("/getProjectList/" + this.nowdeptno).then(res => {
          this.pList = res.data
            // if(this.proForm.pid == 0){
            //       this.proForm.pid = pList[0].pid
            //       
            // }
        })
       },
    },
    watch:{
        isShow(val){
            //val代表父组件传递的新的isShow值
            this.dialogFormVisible = val
            this.getDeptName()
            if(this.mod == 2){
              this.prButShow = false
            }
            this.getProjectList()
            ////////////////////////////////////////////////////////////////////////
             if(this.proForm.date == ''){
               let thisDate = new Date()
               let year = thisDate.getFullYear();
               let month = String(thisDate.getMonth() + 1).padStart(2, '0');
               let day = String(thisDate.getDate()).padStart(2, '0');
               this.proForm.date = year + '-' + month + '-' + day
             }

            if(this.proForm.prNum == ''){
              let dat = this.proForm.date
              let dstr =  dat.replace(/-/g, "");
              for(let i = 0; i < 3; i++){
                    // 生成0-25之间的随机整数，对应a-z
                const randomNum = Math.floor(Math.random() * 26);
                // 转换为对应的字母
                const randomLetter = String.fromCharCode(97 + randomNum); // 97是'a'的ASCII码
                dstr += randomLetter;
              }
              this.proForm.prNum = dstr
            }
            ///////////////////////////////////////////////////////////////////////////
        },
        proInfo:{
            handler(val){
                this.proForm = {...val}
                this.getDetails()
                this.getHistory()
          }
        },
        pdList:{
          handler(val){
            this.totalMoney = 0
           for(let pd of val){
              this.totalMoney += pd.price * pd.number
            }
          }
        },
        proForm: { 
      handler(val){

        console.log(val)
      }
    }
    },
    
}
</script>

<style>

</style>